import { _decorator, Component, Node, game } from 'cc'
import EventManager from '../../Runtime/EventManager'
import { EVENT_ENUM, SHAKE_TYPE_ENUM } from '../../Enum'
const { ccclass, property } = _decorator

/**
 * Predefined variables
 * Name = ShakeManager
 * DateTime = Mon Aug 01 2022 13:40:07 GMT+0800 (中国标准时间)
 * Author = Zero_Y
 * FileBasename = ShakeManager.ts
 * FileBasenameNoExtension = ShakeManager
 * URL = db://assets/Scripts/UI/ShakeManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 * 屏幕震动
 */

@ccclass('ShakeManager')
export class ShakeManager extends Component {
  private isShaking = false
  private oldTime: number = 0
  private oldPos: { x: number; y: number } = { x: 0, y: 0 }
  private type: SHAKE_TYPE_ENUM

  onLoad() {
    EventManager.Instance.on(EVENT_ENUM.SCREEN_SHAKE, this.onShake, this)
  }
  onDestroy() {
    EventManager.Instance.off(EVENT_ENUM.SCREEN_SHAKE, this.onShake)
  }
  onShake(type: SHAKE_TYPE_ENUM) {
    if (this.isShaking) {
      return
    }
    this.type = type
    this.oldTime = game.totalTime
    this.isShaking = true
    this.oldPos = {
      x: this.node.position.x,
      y: this.node.position.y,
    }
  }
  update() {
    if (this.isShaking) {
      const amount = 3
      const fre = 12
      const cur = (game.totalTime - this.oldTime) / 1000
      // 震动时长s
      const totalSecond = 0.2
      const offset = amount * Math.sin(fre * Math.PI * cur)
      if (this.type === SHAKE_TYPE_ENUM.TOP) {
        this.node.setPosition(this.oldPos.x, this.oldPos.y - offset)
      } else if (this.type === SHAKE_TYPE_ENUM.BOTTOM) {
        this.node.setPosition(this.oldPos.x, this.oldPos.y + offset)
      } else if (this.type === SHAKE_TYPE_ENUM.LEFT) {
        this.node.setPosition(this.oldPos.x - offset, this.oldPos.y)
      } else if (this.type === SHAKE_TYPE_ENUM.RIGHT) {
        this.node.setPosition(this.oldPos.x + offset, this.oldPos.y)
      }
      if (cur > totalSecond) {
        this.isShaking = false
        this.node.setPosition(this.oldPos.x, this.oldPos.y)
      }
    }
  }
  stop() {
    this.isShaking = false
  }
}
